var roomId = $("#roomId").val();
var playerId = $("#playerId").val();
var playerName = $("#playerName").val();
var url = "ws://" + window.location.host + "/webSocket/game/" + roomId + "/" + playerId;
var webSocket;

function webSocketOpen(event) {
    console.log("链接服务器成功!");

};

function webSocketOnMessage(event) {
    var command = JSON.parse(event.data);
    switch (command.commandType) {
        case 0:
            receiveChatMessage(command.data);
            break;
        case 2:
            receiveAllocRole(command.data);
            break;
        case 3:
            receiveChooseMc(command.data);
            break;
        case 5:
            receiveVote(command.data);
            break;
        case 7:
            receiveGameOver(command.data);
            break;
        default:
            break;
    }
};

function webSocketOnError(event) {
    console.log("出错");
};

function webSocketOnClose(event) {
    console.log("服务器断开");
};
/**
 * 点击准备按钮，连接服务器
 */
$("#readyButton").on("click", function () {
    webSocket = new WebSocket(url);
    $(this).hide();
    $("#closeButton").show();
    webSocket.onopen = function (event) {
        webSocketOpen(event);
    };
    webSocket.onmessage = function (event) {
        webSocketOnMessage(event);
    };
    webSocket.onclose = function (event) {
        webSocketOnClose(event);
    };
    webSocket.onerror = function (event) {
        webSocketOnError(event);
    }
});

$("#closeButton").on("click", function () {
    webSocket.close();
});
/**
 * 发送聊天信息
 */
$("#chatMessageButton").on("click", function () {
    var chatMessage = $("#chatMessageInput").val();
    if (isEmpty(chatMessage)) {
        return;
    }
    var line = playerName + ":" + chatMessage + "\n";

    var obj = {
        commandType: 0,
        roomId: roomId,
        fromNegotiationPlayerId: playerId,
        data: {
            fromPlayerName: playerName,
            chatMessage: chatMessage
        }
    };
    webSocket.send(JSON.stringify(obj));
    $("#chatMessageList").append(line);
    $("#chatMessageInput").val("");
});

$("#offerBtn").on("click", function () {
    $("#offerBtn").attr("disabled", true);
    offer();
});

/**
 * 收到聊天消息
 * @param data
 */
function receiveChatMessage(data) {
    var line = data.fromPlayerName + ":" + data.chatMessage + "\n";
    $("#chatMessageList").append(line);
}

/**
 * 收到角色分配消息
 * @param data
 */
function receiveAllocRole(data) {

    var issueList = data.issueList;

    for (var index = 0; index < issueList.length; index++) {
        var issue = issueList[index];
        var html = "<tr><td class='am-text-middle' rowspan='" + issue.options.length + "'>" + issue.name + "</td>";
        html += "<td class='am-text-middle' rowspan='" + issue.options.length + "'>" + data.role.preferenceWeight[issue.name] + "</td>";
        for (var i = 0; i < issue.options.length; i++) {
            html += i == 0 ? "" : "<tr>";
            var key = issue.options[i].name;
            html += "<td>" + key + "</td>";
            html += "<td>" + data.role.optionValues[key] + "</td></tr>";
        }

        $("#preferencesTable").append(html);
    }
    var playerList = data.playerList;
    console.log(playerList);
    for (var index = 0; index < playerList.length; index++) {
        var html = "<tr><td>" + playerList[index].name + "</td>";
        html += "<td>" + playerList[index].type + "</td></tr>";
        $("#playerTable").append(html);
    }
}

/**
 * 收到出价人的选定
 * @param data
 */
function receiveChooseMc(data) {
    if (playerId == data["mcId"]) {
        $("#offerBtn").removeAttr("disabled");
        alert("请完成出价");
    } else {
        var line = "系统消息:" + "现在等待玩家:" + data["mcName"] + "进行出价。\n";
        $("#chatMessageList").append(line);
    }
}

/**
 * 出价
 */
function offer() {
    var selectDoms = $('#offerForm').find('select'),
        len = selectDoms.length,
        data = {};
    for (var i = 0; i < len; i++) {
        var select = $(selectDoms[i]),
            name = select.attr('name'),
            value = select.val();
        data[name] = value;
    }

    var result = {
        commandType: 4,
        roomId: roomId,
        fromNegotiationPlayerId: playerId,
        data: data
    };
    webSocket.send(JSON.stringify(result));
    console.log(result);

}

/**
 * 收到要求表决的请求
 * @param data
 */
function receiveVote(data) {

    $("#voteConfirmPlayerName").html("玩家：" + data["offerPlayerName"] + "的出价，请表决！")
    $("#voteConfirmScore").html(data["score"]);
    var offerData = "";
    for (var key in data["offerData"]) {
        offerData += "<li>";
        offerData += key + ":" + data.offerData[key];
        offerData += "</li>";
    }
    $("#voteConfirmList").empty();
    $("#voteConfirmList").append(offerData);
    setTimeout(function (args) {
        $('#voteConfirm').modal({
            relatedTarget: this,
            onConfirm: function () {
                var result = {
                    commandType: 6,
                    roomId: roomId,
                    fromNegotiationPlayerId: playerId,
                    data: {
                        voteResult: true
                    }
                };
                webSocket.send(JSON.stringify(result));
            },
            onCancel: function () {
                var result = {
                    commandType: 6,
                    roomId: roomId,
                    fromNegotiationPlayerId: playerId,
                    data: {
                        voteResult: false
                    }
                };
                webSocket.send(JSON.stringify(result));
            }
        });
    }, 0)

}


function receiveGameOver(data) {
    alert("游戏结束");
    webSocket.close();
    this.window.opener = null;
    window.close();
}

/**
 * 判断字符串是否为null或空
 * @param obj
 * @returns {boolean}
 */
function isEmpty(obj) {
    if (obj === null) return true;
    if (typeof obj === 'undefined') {
        return true;
    }
    if (typeof obj === 'string') {
        if (obj === "") {
            return true;
        }
        var reg = new RegExp("^([ ]+)|([　]+)$");
        return reg.test(obj);
    }
    return false;
}